package com.zhengqiangblog.blog.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.zhengqiangblog.blog.admin.form.LoginForm;
import com.zhengqiangblog.blog.model.AdminAccount;
import com.zhengqiangblog.blog.service.AdminAccountService;
import com.zhengqiangblog.core.ApplicationContext;
import com.zhengqiangblog.core.Model;

public class AdminAccountAction {

	private static final Logger logger = Logger.getLogger(AdminAccountAction.class);

	private AdminAccountService adminAccountService = ApplicationContext.get(AdminAccountService.class);

	public AdminAccountAction() {
		logger.info("AdminAccountAction initializing...");
	}

	public String execute(Model model) {
		return "LOGIN";
	}

	public String login(Model model, LoginForm loginForm) throws Exception {
		String login = loginForm.getLogin();
		String password = loginForm.getPassword();
		List<String> messages = new ArrayList<String>();
		if (StringUtils.isBlank(login)) {
			messages.add("帐号不能为空");
		}
		if (StringUtils.isBlank(password)) {
			messages.add("密码不能为空");
		}
		if (messages.size() > 0) {
			model.addAttribute("messages", messages);
			return "LOGIN";
		}
		login = login.trim().toLowerCase();
		AdminAccount adminAccount = adminAccountService.login(login, password);
		if (adminAccount == null) {
			messages.add("帐号/密码不正确，请重新登录");
			model.addAttribute("messages", messages);
			return "LOGIN";
		} else {
			HttpSession session = model.getSession();
			session.setAttribute("adminAccount", adminAccount);
			return "ADMIN_HOME";
		}
	}

}
